// $Id: networkconstant.cpp 63 2004-10-22 14:33:20Z jonas $
#include "networkconstant.h"
//#include <stdlib.h>
#define min(a,b) (((a)<(b))?(a):(b))

// #include <iostream>

/**
 * Init members.
 *
 * @param nodes A pointer to a stl list of all nodes.
 * @param speed The constant speed in which all nodes shall transfer.
 */
NetworkConstant::NetworkConstant(list<Node *> *nodes, int speed)
	: Network(nodes), m_speed(speed)
{
}

/**
 * @todo Write documentation
 */
/*NetworkConstant::~NetworkConstant()
{
}*/

/**
 * Find all transfers in all nodes and transfer them with a constant speed.
 */
void NetworkConstant::transfer()
{
	// For all nodes...
	for (list<Node *>::iterator node=m_nodes->begin(); node!=m_nodes->end(); node++) {
		Transfer *transfer;
		int index = 0;
		// For all transfers (in nodes)
		while ((transfer = (*node)->getTransfer(index++))) {
				// Transfer m_speed bytes if there is so many bytes to transfer
				//int bytesCount = min((unsigned int) m_speed, transfer->m_file->m_size - transfer->m_progress);
			// Transfer m_speed bytes if there is so many bytes to transfer (use size of original file instead of the local file in the datastore because the transfer speed is VERY reliable!
			// Get a pointer to the file to manipulate (transfer to)
			StoredFile *file = ((Node *) transfer->m_destination)->getStoredFile((File *) transfer->m_file->m_file);
			assert(file);

			//int bytesCount = min((unsigned int) m_speed, transfer->m_file->m_file->m_size - transfer->m_progress);
			int bytesCount = min((unsigned int) m_speed, transfer->m_file->m_file->m_size - file->m_size);

			// Touch the active files
			file->touch();
			((StoredFile *) transfer->m_file)->touch();

			// Update the process counter
			//transfer->m_progress += bytesCount;
			//file->m_size = transfer->m_progress;
			file->m_size += bytesCount;
		}
	}
}
